
from flask import Response, request,json,make_response
from app.model import Contactlist
from . import vueapi

@vueapi.route('/')
def hello():
    return 'Hello Vue API'

#查询记录
@vueapi.route('/contactList')
def get():
    contacts = Contactlist.objects.filter()
    list = []
    cons = {
        'id': 0,
        'name': '',
        'tel': ''
    }
    #print(contacts[0].id)
    for contact in contacts:
        cons = {
            'id': str(contact.id),
            'name': contact.name,
            'tel': contact.tel
        }
        list.append(cons)
        #print(str(contact.id) + ' ' + contact.name + ' ' + contact.tel)
    res = make_response(json.dumps(list))
    res.headers['Access-Control-Allow-Origin'] = '*'

    return res

#保存记录;
@vueapi.route('/contact/new/json', methods=["POST"])
def save_data():
    #获取参数信息;
    data = eval(request.data.decode('utf-8'))
    name = data.get('name')
    tel =  data.get('tel')
    print(name+'...'+ tel)
    #获取ID
    count = Contactlist.objects.filter().count()+1
    #实例化对象；
    contact = Contactlist(id=count,name= name,tel=tel)
    contact.save()
    contacts = [{
        'name': name,
        'tel': tel
    },]
    #以下为解决跨域请求
    res = make_response(json.dumps(contacts))
    res.headers['Access-Control-Allow-Origin'] = '*'
    res.headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS, DELETE'
    res.headers['Access-Control-Allow-Credentials'] = 'true'
    return res

#更新记录
@vueapi.route('/contact/edit',methods=['PUT'])
def update_data():
    #获取参数值
    data = eval(request.data.decode('utf-8'))
    id = data.get('id')
    name = data.get('name')
    tel = data.get('tel')
    #根据参数获取记录
    contact = Contactlist.objects.get_or_404(id=id)
    #修改查询出记录的内容；
    contact.id = id
    contact.name = name
    contact.tel = tel
    #保存记录
    contact.save()
    res = make_response('OK')
    res.headers['Access-Control-Allow-Origin'] = '*'
    res.headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS, DELETE'
    res.headers['Access-Control-Allow-Credentials'] = 'true'
    return res

#删除记录
@vueapi.route('/contact', methods=['delete'])
def delete_data():
    id = request.args['id']
    contact = Contactlist.objects.get_or_404(id = id)
    if contact:
        contact.delete()
    res = make_response("OK")
    res.headers['Access-Control-Allow-Origin'] = '*'
    res.headers['Access-Control-Allow-Credentials'] = 'true'
    return res

#添加记录
@vueapi.route('/add')
def add():
    contact = Contactlist(id=1, name="张三", tel="13698750001")
    contact.save()
    contact = Contactlist(id=2, name="李四",tel="13698754651")
    contact.save()
    contact = Contactlist(id=3, name="王五", tel="13698754678")
    contact.save()
    contact = Contactlist(id=4, name="杨三", tel="13698754679")
    contact.save()
    return Response('OKKKK')